#pragma once
#include <iostream>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;

template<class T>
class UnionFindSet
{
public:
	UnionFindSet(size_t n)
	{
		_ufs.resize(n, -1);
	}

	size_t size()
	{
		size_t count = 0;
		for (int i = 0; i < _ufs.size();++i)
		{
			if (_ufs < 0)
				count++;
		}
		return count;
	}

	bool Union(T v1, T v2)
	{
		int root1 = Find(v1);
		int root2 = Find(v2);
		if (root1 == root2)
			return false; 

		if (abs(_ufs[root1]) < abs(_ufs[root2]))
			swap(root1, root2);

		_ufs[root1] += _ufs[root2];
		_ufs[root2] = root1;

		return true;
	}

	int Find(T x)
	{
		int root = x;
		while (_ufs[root] >= 0)
		{
			root = _ufs[root];
		}
		return root;
	}

	bool InSet(T v1, T v2)
	{
		return Find(v1) == Find(v2);
	}

private:
	vector<T> _ufs;
};